/*******************************************************************************
 * Copyright 2011-2013 Sergey Tarasevich
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.hbu.imagePackage;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.hbu.housingbrokerug.activities.parserFromUrl;
import com.hbu.housingbrokeruganda.Parser.JSONParser;
import com.hub.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

/**
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 */
public class ImagePagerActivity extends BaseActivity {
	ProgressDialog pDialog;
	private static final String STATE_POSITION = "STATE_POSITION";
	parserFromUrl parser=new parserFromUrl();
	private JSONParser urlRequest=new JSONParser();
	DisplayImageOptions options=parser.getOptions();
	String[] galleryData=null;
	private static final String TAG_SUCCESS_GALLERY = "success";
	
	ViewPager pager;

		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.header);	
			setContentView(R.layout.gallery_view);		
			new getPageDisplay().execute();			
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt(STATE_POSITION, pager.getCurrentItem());
	}

	private class ImagePagerAdapter extends PagerAdapter {

		private String[] images;
		private LayoutInflater inflater;

		ImagePagerAdapter(String[] iMAGES2) {
			this.images = iMAGES2;
			inflater = getLayoutInflater();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}

		@Override
		public void finishUpdate(View container) {
		}

		@Override
		public int getCount() {
			return images.length;
		}

		@Override
		public Object instantiateItem(ViewGroup view, int position) {
			View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
			ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
			final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);

			imageLoader.displayImage(images[position], imageView, options, new SimpleImageLoadingListener() {
				@Override
				public void onLoadingStarted(String imageUri, View view) {
					spinner.setVisibility(View.VISIBLE);
				}

				@Override
				public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
					String message = null;
					switch (failReason.getType()) {
						case IO_ERROR:
							message = "Input/Output error";
							break;
						case DECODING_ERROR:
							message = "Image can't be decoded";
							break;
						case NETWORK_DENIED:
							message = "Downloads are denied";
							break;
						case OUT_OF_MEMORY:
							message = "Out Of Memory error";
							break;
						case UNKNOWN:
							message = "Unknown error";
							break;
					}
					Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();

					spinner.setVisibility(View.GONE);
				}

				@Override
				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
					spinner.setVisibility(View.GONE);
				}
			});

			((ViewPager) view).addView(imageLayout, 0);
			return imageLayout;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view.equals(object);
		}

		@Override
		public void restoreState(Parcelable state, ClassLoader loader) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View container) {
		}
	}
	
	
	
	public class getPageDisplay extends AsyncTask<String, String, String> {
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(ImagePagerActivity.this);
			pDialog.setMessage("Loading Houses From Server. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}
		
		
		

		@Override
		protected String doInBackground(String... params) {
			Bundle bundle=getIntent().getExtras();
			JSONObject json_gallery=urlRequest.makeHttpRequest(parser.getIpOrDomain()+"get_single_unit_gallery_data.php","GET"
					, parser.getParametersSingleUnitGallery(bundle.getString("UNIT_ID")));		

			try{	
			int  success_gallery = json_gallery.getInt(TAG_SUCCESS_GALLERY);
			if(success_gallery==1){
			 JSONArray jArray=json_gallery.getJSONArray("unit_gallery");	
			 Log.d("PASSED1",jArray+"");
			 
			 galleryData=new String[jArray.length()];
			
			 for(int i=0;i<jArray.length();i++){	
				 
			JSONObject json1=jArray.getJSONObject(i);
			 
			galleryData[i]=parser.getIpOrDomain()+json1.getString("urls_image");
			Log.d("IMAGES From",galleryData[i]);
		     
		}
			 
			Log.d("", galleryData.length+" Passsed");
			
	        }
			 else{ 
				 galleryData=new String[1];
				 galleryData[1]=parser.getIpOrDomain()+parser.getDefaultImage();
			 }
			
			}catch(Exception  e){
				Log.e("ERROR GETTING DATA TO ARRAY", e.toString());							
			}
			
			
			
			
			return null;
		}
		

		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					
					 try{
							pager = (ViewPager) findViewById(R.id.pager);
							pager.setAdapter(new ImagePagerAdapter(galleryData));
						//		pager.setCurrentItem(pagerPosition);
						}catch(Exception e){
							Log.d("CRASHED AT LAST","");
							
						}
		
				}
			});
		}	

	}
	
	
}